package com.atguigu.spzx.gateway.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class GatewayConfig {
    @Resource
    RedisTemplate redisTemplate;
    @PostConstruct
    public void init(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }
    //统一跨域配置
    @Bean
    public CorsWebFilter corsWebFilter(){

        UrlBasedCorsConfigurationSource corsConfigSource
                 = new UrlBasedCorsConfigurationSource();
        //一个跨域配置
        CorsConfiguration config = new CorsConfiguration();
//        config.addAllowedOrigin("http://www.spzx.com");
        config.addAllowedOriginPattern("*");//允许哪些前端资源服务器跨域访问
        config.addAllowedMethod("*");//允许跨域访问的请求方式
        config.addAllowedHeader("*");//允许跨域访问携带的头
        config.setAllowCredentials(true);//是否允许携带cookie跨域访问
        //给所有访问网关的请求添加跨域配置  /**通配所有
        corsConfigSource.registerCorsConfiguration("/**" , config);
        return new CorsWebFilter(corsConfigSource);
    }

}
